package logic

import (
	"context"
	"three-sxp/models/mysql"

	"three-sxp/userrpc/internal/svc"
	"three-sxp/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	user, _ := mysql.GetUserInfo(mysql.User{
		Mobile: in.Mobile,
	})
	if user.ID == 0 {
		u, err := mysql.CreateUser(mysql.User{
			Mobile:   in.Mobile,
			Password: in.Password,
		})
		if err != nil {
			return &userrpc.UserLoginResponse{
				Code: 400,
				Msg:  "注册失败",
			}, nil
		}
		return &userrpc.UserLoginResponse{
			Code:   200,
			Msg:    "注册成功，登录成功",
			UserId: int64(u.ID),
		}, nil
	}
	if user.Password != in.Password {
		return &userrpc.UserLoginResponse{
			Code: 400,
			Msg:  "密码错误",
		}, nil
	}
	return &userrpc.UserLoginResponse{
		Code:   200,
		Msg:    "登录成功",
		UserId: int64(user.ID),
	}, nil
}
